import React, { PureComponent, Fragment } from 'react';

import { isEqual } from 'lodash';
import { getAddressNameByCode } from '@/utils/utils';
import { Table, Button } from 'antd';

import AddGardenModel from './AddGardenModal';

interface TableGardenDateType {
  id: number;
  name: string;
  address: string;
  parea_code: string;
  selected: boolean;
}

interface TableGardenProps {
  loading?: boolean;
  value?: TableGardenDateType[];
  onChange?: (value: TableGardenDateType[]) => void;
}

interface TableGardenState {
  loading?: boolean;
  data?: TableGardenDateType[];
  current: number,
  pageSize: number | undefined,
  selectedRowKeys: any,
  gardenModel: boolean,
}
class TableGarden extends PureComponent<TableGardenProps, TableGardenState> {
  columns = [
    {
      title: '社区名称',
      dataIndex: 'name',
      width: '33.33%',
    },
    {
      title: '物业',
      dataIndex: 'address',
      render: (text: string) => (
        <div className="wordOmit">{ text }</div>
      ),
    },
    {
      title: '地区',
      width: '28%',
      dataIndex: 'parea_code',
      render: (text: any, record: any) => (
        <div>
          {text && getAddressNameByCode({
            pareaCode: text || '',
            caredCode: record.carea_code || '',
            dareaCode: record.darea_code || '',
          })}
        </div>
      ),
    },
  ];

  constructor(props: TableGardenProps) {
    super(props);
    this.state = {
      loading: false,
      data: props.value,
      current: 1,
      pageSize: 10,
      selectedRowKeys: [],
      gardenModel: false,
    };
  }

  componentDidUpdate(prevProps: any) {
    const { value } = this.props;

    if (!isEqual(prevProps.value, value)) {
      const data = (value || []).reduce((origin: any, item: any) => {
        if (item) {
          item.selected = true;
          origin.push(item);
        }
        return origin;
      }, []);

      this.updateState(data, value);
    }
  }

  updateState = (data: any, value: any) => {
    const selectedRowKeys = value && value.map((item: { id: number }) => item && item.id);
    this.setState({ data, selectedRowKeys });
  };

  /**
   * 删除社区
   */
  handleDelGarden = (id: number) => {
    const { data = [] } = this.state;
    const newData = data.filter(item => item.id !== id);
    this.setState({ data: newData });

    const { onChange } = this.props;
    if (onChange) {
      onChange(newData);
    }
  }

  // 分页和选择页码
  onSizeChange = (current: number, pageSize: any) => this.setState({ current, pageSize });

  // 选中项发生变化
  onSelectChange = (selectedRowKeys: any) => {
    this.setState({ selectedRowKeys });

    const { data = [] } = this.state;
    const newData = data.reduce((origin: any, item: any) => {
      if (selectedRowKeys.find((id: number) => id === item.id)) {
        item.selected = true;
      } else {
        item.selected = false;
      }
      origin.push(item);
      return origin;
    }, []);

    const { onChange } = this.props;
    if (onChange) onChange(newData);
  };

  /**
   * 显示弹窗/隐藏弹窗
   */
  handleGardenModel = (gardenModel:boolean) => this.setState({ gardenModel });

  /**
   * 确定添加
   */
  handleAddGardens = (gardens: []) => {
    const { data = [] } = this.state;
    const newGardens = gardens
      .filter((garden: { id: number }) => !data.find(item => item.id === garden.id));
    const newData = [...data, ...newGardens];
    const selectedRowKeys = newData.map((item: { id: number }) => item.id);

    this.setState({
      data: newData,
      selectedRowKeys,
    });

    const { onChange } = this.props;
    if (onChange) {
      onChange(newData);
    }
  }

  render() {
    const { gardenModel } = this.state;
    const {
      loading,
      data,
      pageSize,
      current,
      selectedRowKeys,
    } = this.state;

    const pagination = data ? {
      total: data ? data.length : 0,
      pageSize,
      current: current || 1,
      onChange: this.onSizeChange,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onSizeChange,
    } : {};

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    return (
      <Fragment>
        <Button
          type="primary"
          size="small"
          style={{ background: '#58c5fd', border: 0, marginBottom: 16 }}
          onClick={() => this.handleGardenModel(true)}
        >
          添加社区
        </Button>

        <Table
          rowKey="id"
          loading={loading}
          columns={this.columns}
          dataSource={data}
          pagination={pagination}
          rowSelection={rowSelection}
          className="tableList statementTable"
        />

        <AddGardenModel
          gardenModel={gardenModel}
          hideGardenModel={() => this.handleGardenModel(false)}
          saveGardens={this.handleAddGardens}
        />
      </Fragment>
    );
  }
}

export default TableGarden;
